import { Switch, Space, Tooltip, Button, Dropdown, theme } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from 'react-i18next';
import type { SwitchProps } from "antd";
import useThemeAnimation from '@/hooks/useThemeAnimation';
const { useToken } = theme;

export const ThemeController = () => {
  const { t, i18n } = useTranslation();
  const { token } = useToken();
  const toggleAnimationTheme = useThemeAnimation();

  // 修复初始化逻辑
  const getInitialState = (key: string, defaultValue: any) => {
    try {
      const saved = localStorage.getItem("theme");
      return saved ? JSON.parse(saved)[key] ?? defaultValue : defaultValue;
    } catch {
      return defaultValue;
    }
  };

  const [isDark, setIsDark] = useState(() => getInitialState("isDark", false));
  const [isCompact, setIsCompact] = useState(() => getInitialState("isCompact", false));
  const [lang, setLanguage] = useState(() => getInitialState("lang", "zh"));

  // 同步语言到 i18n
  useEffect(() => {
    i18n.changeLanguage(lang);
  }, [lang]);

  // 持久化存储
  useEffect(() => {
    const themeConfig = { isDark, isCompact, lang };
    localStorage.setItem("theme", JSON.stringify(themeConfig));
    window.dispatchEvent(
      new StorageEvent("storage", {
        key: "theme",
        newValue: JSON.stringify(themeConfig),
      })
    );
  }, [isDark, isCompact, lang]);

  const items = [
    {
      key: 'zh',
      label: '中文',
      onClick: () => setLanguage('zh'),
    },
    {
      key: 'en',
      label: 'English',
      onClick: () => setLanguage('en'),
    },
  ];
  const handleThemeChange: SwitchProps['onChange'] = (checked, event) => {
    setIsDark(checked);
    toggleAnimationTheme(event as React.MouseEvent<HTMLElement>, checked);
  };
  return (
    <Space>
      <Tooltip title={t('darkMode')}>
        <Switch
          checked={isDark}
          onChange={handleThemeChange}
          checkedChildren="🌙"
          unCheckedChildren="☀️"
        />
      </Tooltip>

      <Tooltip title={t('compactMode')}>
        <Switch
          checked={isCompact}
          onChange={setIsCompact}
          checkedChildren="📏"
          unCheckedChildren="📏"
        />
      </Tooltip>

      <Dropdown menu={{ items }} placement="bottomRight">
        <Button type="text" style={{ color: token.colorText }}>
          {t('changeLanguage')} ({lang.toUpperCase()})
        </Button>
      </Dropdown>
    </Space>
  );
};